package com.hidao.platform.zike.service.impl;

import java.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.hidao.basic.common.bean.Page;
import com.hidao.basic.common.bean.Pageable;
import com.hidao.basic.data.util.BeanMapper;
import com.hidao.platform.ssh.basic.XBaseServiceImpl;
import com.hidao.platform.zike.dao.CustomerDao;
import com.hidao.platform.zike.entity.Customer;
import com.hidao.platform.zike.service.CustomerService;
import com.hidao.platform.zike.api.vo.CustomerVo;

@Service
public class CustomerServiceImpl extends XBaseServiceImpl<Customer, Integer, CustomerVo> implements CustomerService {

	private final static Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);
	@Autowired
	private CustomerDao customerDao;

	@Override
	public void postConstruct() {
		this.setBaseDao(customerDao);
	}

	@Override
	public Page<Customer> findByPage(CustomerVo customerVo, Pageable pageable) {
		String queryStr = "from Customer u where 1=1 ";
		List<Object> params = new ArrayList<Object>();
		if (customerVo != null) {
			/*if (!StringUtils.isEmpty(vo.getType())) {
				queryStr += " and u.type=? ";
				params.add(vo.getType());
			}*/
		}
		return this.customerDao.findPage(queryStr, pageable, params.toArray());
	}

	@Override
	public Page<CustomerVo> findBySqlPage(CustomerVo customerVo, Pageable pageable) {
		String sql=env.getProperty("sql.queryCustomer");
		List<Object> params = new ArrayList<Object>();
		if (customerVo != null) {

		}
		Class clazz=customerVo.getClass();
		//pageable.setSort(new Sort(Direction.DESC, "a.orderCount"));
		Page<CustomerVo> page = this.customerDao.findSqlPage(sql, pageable,clazz, params.toArray());

		return page;
	}

	@Override
	@Transactional(readOnly = false)
	public void saveOrUpdate(CustomerVo customerVo) {
		Customer customer = null;
		if (customerVo.getId() != null) {
			customer = this.customerDao.get(customerVo.getId());
			customer.setUpdateTime(new Date());
			BeanMapper beanMapper = BeanMapper.beanMapperFactory();
			beanMapper.map(customer, customer);
		} else {
			customer = new Customer();
			BeanUtils.copyProperties(customerVo, customer);
			this.save(customer);
		}
	}
}
